﻿using System;
using System.Threading;
using FibMatrix.Utils;
using UnityEngine;

public class AndroidUtil
{
	public static void ReportException(string message, string stackTrace)
	{
		if (Thread.CurrentThread.ManagedThreadId != CommonUtil.mainThreadId)
		{
			AndroidJNI.AttachCurrentThread();
		}
		CallAndroidUtilStatic("reportException", message, stackTrace);
	}

	public static string GetPackageName()
	{
		string packageName = null;
		using (AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
		{
			using (AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity"))
			{
				packageName = jo.Call<string>("getPackageName");
			}
		}

		return packageName;
	}

	public static void SetSharedPreference(string key, string value)
	{
		using (AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
		{
			using (AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity"))
			{
				using (AndroidJavaObject prefs = jo.Call<AndroidJavaObject>("getPreferences", 0))
				{
					using (AndroidJavaObject editor = prefs.Call<AndroidJavaObject>("edit"))
					{
						using (AndroidJavaObject editor2 = editor.Call<AndroidJavaObject>("putString", key, value))
						{
							editor.Call<bool>("commit");
						}
					}
				}
			}
		}
	}

    public static T CallAndroidUtilStatic<T>(string funcName, params object[] args)
	{
		T result = default(T);
		try
		{
			using (AndroidJavaClass util = new AndroidJavaClass("com.rivergame.util.RGAndroidUnityHelper"))
			{
				result = util.CallStatic<T>(funcName, args);
			}

		}
		catch (Exception e)
		{
			Debug.LogException(e);
		}
		return result;
	}

	public static T GetStatic<T>(string className, string fieldName)
	{
		T result = default(T);
		try
		{
			using (AndroidJavaClass util = new AndroidJavaClass(className))
			{
				result = util.GetStatic<T>(fieldName);
			}

		}
		catch (Exception e)
		{
			Debug.LogException(e);
		}
		return result;
	}

	public static T GetStatic<T>(AndroidJavaClass cls, string fieldName)
	{
		T result = default(T);
		try
		{
			result = cls.GetStatic<T>(fieldName);
		}
		catch (Exception e)
		{
			Debug.LogException(e);
		}
		return result;
	}

	public static void CallStatic(string className, string funcName, params object[] args)
	{
		try
		{
			using (AndroidJavaClass util = new AndroidJavaClass(className))
			{
				util.CallStatic(funcName, args);
			}

		}
		catch (Exception e)
		{
			Debug.LogException(e);
		}
	}

	private static void CallAndroidUtilStatic(string funcName, params object[] args)
	{
		try
		{
			using (AndroidJavaClass util = new AndroidJavaClass("com.rivergame.util.RGAndroidUnityHelper"))
			{
				util.CallStatic(funcName, args);
			}

		}
		catch (Exception e)
		{
			Debug.LogException(e);
		}
	}
}
